package cn.zhuzicc;

import java.util.concurrent.RecursiveTask;

/**
 * @author zhaoxiang
 * @version 1.0
 * @description
 * @Date 2021/1/10 16:05
 */
public class ForkJoinCalculateBak extends RecursiveTask<Long> {

    private static final long serialVersionUID = 123655995645L;

    // 起始标志位
    private long start;
    // 终止标志位
    private long end;

    // 设置阀值
    private static final long  THRESHOLD = 100000;

    public ForkJoinCalculateBak(long start, long end) {
        this.start = start;
        this.end = end;
    }

    /**
     * The main computation performed by this task.
     *
     * @return the result of the computation
     */
    @Override
    protected Long compute() {
        long length = end - start;
        if(length <= THRESHOLD){
            long sum = 0;
            for (long i = start; i <= end ; i++) {
                sum += i;
            }
            return sum;
        } else {
            long middle = (start + end)/2;
            ForkJoinCalculateBak left = new ForkJoinCalculateBak(start, middle);
            ForkJoinCalculateBak right = new ForkJoinCalculateBak(middle + 1, end);

            // 拆分子任务，同时压入队列
            left.fork();
            right.fork();

            return left.join() + right.join();
        }
    }
}
